<script setup>

import MyTable from "@/components/constant/myTable.vue";
import {addCarmine, delCarmine, getCarmineList} from "@/api/httpApi/carmineApi.js";
import {successCode} from "@/api/httpApi/base/http.js";
import {constantStore} from "@/stores/constantStore.js";
import {onMounted, ref, reactive} from "vue";
import {error, success, warning} from "@/api/myMessage.js";
import MySelect from "@/components/constant/mySelect.vue";
import {getUserList} from "@/api/httpApi/userApi.js";

/**
 * 分页相关
 */
let pageObj = ref({
  currentPage: 1,
  pageSize: 23,
  totalPages: 10,
  totalCount: 1,
  first: false,
  last: false,
})
const money = ref()
const userId = ref()
const used = ref()
const startTime = ref()
const endTime = ref()

onMounted(() => {
  initCarmineList();
  initUserList();
})
const carmineList = ref()

function initCarmineList() {
  startTime.value = timeValue.value && timeValue.value[0] ? timeValue.value[0].getTime() : "";
  endTime.value = timeValue.value && timeValue.value[1] ? timeValue.value[1].getTime() : "";
  getCarmineList(pageObj.value.currentPage, pageObj.value.pageSize, money.value, userId.value, used.value, startTime.value, endTime.value).then(res => {
    if (res.code === successCode) {
      carmineList.value = res.data.content;
      constantStore().copyPage(pageObj, res.data);
    }
  })
}

const carmineMoneyShow = ref(false);
const carmineObj = ref({
  money: 0,
  count: 1,
});

function createCarmine() {
  if (carmineObj.value.money <= 0) {
    warning("开卡金额必须大于0");
    return;
  }
  if (carmineObj.value.count <= 0) {
    warning("开卡数量不得小于1");
    return;
  }
  addCarmine(carmineObj.value).then(res => {
    if (res.code === successCode) {
      success(res.message);
      initCarmineList();
      carmineObj.value.money = "";
      carmineMoneyShow.value = false
    } else {
      error(res.message)
    }
  })
}

function copyList() {
  let msg = "";
  selectList.value.forEach((item) => {
    msg = msg + item.uuid + "\n"
  })
  fallbackCopy(msg, true);
  // navigator.clipboard.writeText(msg).then(function () {
  //   success('卡密批量复制成功');
  // }).catch(function (err) {
  //   error('卡密批量复制失败');
  //   console.log(err)
  // });
}

function copyItem(item) {
  let msg = item.uuid;
  fallbackCopy(msg, false)
}

function fallbackCopy(text, isList) {
  let msg = "卡密复制成功";
  let msgErr = "卡密复制失败";
  if (isList && isList === "true") {
    let msg = "卡密批量复制成功";
    let msgErr = "卡密批量复制失败";
  }
  if (navigator.clipboard) {
    navigator.clipboard.writeText(text).then(function () {
      success(msg);
    }).catch(function (err) {
      error(msgErr);
      console.log(err)
    });
  } else {
    const textarea = document.createElement('textarea');
    textarea.value = text;
    textarea.style.position = 'fixed'; // 避免滚动
    document.body.appendChild(textarea);
    textarea.select();
    try {
      document.execCommand('copy');
      success(msg);
    } catch (err) {
      error(msgErr + "，不支持Clipboard API，请手动复制");
    }
    document.body.removeChild(textarea);
  }
}

const selectList = ref([])

function selectChange(arr) {
  selectList.value = arr;
}

let userSelect = ref({});

function initUserList() {
  getUserList(1, 99999).then(res => {
    if (res.code === successCode) {
      userSelect.value = constantStore().listToSelect(res.data.content, "name", "id");
    }
  })
}

/**
 * 初始化相关
 */
let carmineMapping = [
  {
    label: "金额",//表头名称 必填
    prop: "money",//数据对应字段 必填
    propConfig: {
      align: "center",//对齐方式 非必填 不写默认左对齐
      type: "text",// 非必填 不写默认text   text(文本) selectText(根据给定列表，选择内容)  tag(标签)  Switch(开关)  image(图片)
      fixed: 'left',//固定列的位置
    },
  },
  {
    label: "卡 密",
    prop: "uuid",
    propConfig: {
      align: "center",
      width: "400",
      type: "text",
    }
  },
  {
    label: "是否使用",
    prop: "used",
    propConfig: {
      align: "center",
      width: "400", type: "tag",
      stateMapping: [
        {type: "danger", data: 0, msg: "未使用"},
        {type: "success", data: 1, msg: "已使用"}
      ]
    }
  },
  {
    label: "激活用户",
    prop: "userName",
    propConfig: {
      align: "center",
      width: "400",
      type: "text",
    }
  },
  {
    label: "创建时间",
    prop: "createTime",
    propConfig: {
      align: "center",
      width: "200",
      type: "text",
    },
  },
  {
    label: "激活时间",
    prop: "updateTime",
    propConfig: {
      align: "center",
      width: "200",
      type: "text",
    },
  },
]

const shortcuts = [
  {
    text: '最近一天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setDate(start.getDate() - 1)
      return [start, end]
    },
  },
  {
    text: '最近三天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setDate(start.getDate() - 3)
      return [start, end]
    },
  },
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setDate(start.getDate() - 7)
      return [start, end]
    },
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setMonth(start.getMonth() - 1)
      return [start, end]
    },
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setMonth(start.getMonth() - 3)
      return [start, end]
    },
  },
  {
    text: '最近一年',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setMonth(start.getMonth() - 12)
      return [start, end]
    },
  },
]
const timeValue = ref([]);
</script>
<template>
  <div class="carmine-box">
    <div class="carmine-table-box">
      <my-table :data-list="carmineList"
                @after-edit="initCarmineList()"
                :del-action="(ids)=>delCarmine(ids)"
                title="卡密设置"
                @select-change="selectChange"
                :btn-config="{add:false,update:false,del:true}"
                :mapping="carmineMapping" :can-select="true">
        <template #buttonAdd>
          <div class="button-box-item">
            <el-button type="primary" @click="copyList">批量复制</el-button>
          </div>
          <div class="button-box-item">
            <el-button type="primary" @click="carmineMoneyShow=true">新增卡密</el-button>
          </div>
          <div class="button-box-item">
            <el-input-number v-model="money" style="width:18rem;margin: 0 0.5rem" placeholder="输入卡密金额" clearable/>
          </div>
          <div class="button-box-item">
            <my-select v-model="used" style="margin: 0 0.5rem" placeholder="选择卡密状态"
                       :option="[{label:'未激活',value: 0},{label:'已激活',value: 1}]"/>
          </div>
          <div class="button-box-item">
            <my-select v-model="userId" style="margin: 0 0.5rem" placeholder="选择激活用户" :option="userSelect"/>
          </div>
          <div class="button-box-item">
            <el-date-picker
                style="margin: 0 0.5rem;"
                format="YYYY-MM-DD HH:mm:ss"
                v-model="timeValue"
                type="datetimerange"
                :shortcuts="shortcuts"
                range-separator=" <--> "
                :arrow-control="true"
                start-placeholder="开始(激活时间)"
                end-placeholder="截止(激活时间)"/>
          </div>
          <div class="button-box-item">
            <el-button type="primary" @click="initCarmineList">搜 索</el-button>
          </div>


        </template>
        <template #tableBtnAdd="scope">
          <el-button type="primary" size="small" @click="copyItem(scope.row)">复制</el-button>
        </template>
      </my-table>
    </div>
    <div class="carmine-page-box">
      <el-pagination
          v-model:current-page="pageObj.currentPage"
          v-model:page-size="pageObj.pageSize"
          :page-sizes="constantStore().pageSizes"
          size="default"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageObj.totalCount"
          @size-change="initCarmineList"
          @current-change="initCarmineList"/>
    </div>
    <div class="carmine-dialog-box">
      <el-dialog v-model="carmineMoneyShow" title="卡密金额" width="500">
        <el-form label-width="auto" style="max-width: 600px">
          <el-form-item label="开卡金额">
            <el-input-number style="width: 30rem" v-model="carmineObj.money" placeholder="请输入金额"/>
          </el-form-item>
          <el-form-item label="开卡数量">
            <el-input-number style="width: 30rem" v-model="carmineObj.count" placeholder="请输入开卡数量"/>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button type="danger" @click="carmineMoneyShow=false">取 消</el-button>
          <el-button type="success" @click="createCarmine">确 定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<style scoped lang="scss">

</style>